package com.tsing.ipcliveserver.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;

/**
 * 异步转码
 *
 * @author TheTsing
 */
@Service
public class AsyncTranscodeHandler {

    private static final Logger log = LoggerFactory.getLogger(AsyncTranscodeHandler.class);

    @Async
    public void handlerInputStream(WebSocketSession session, Process ffmpegProcess) {
        try (InputStream inputStream = ffmpegProcess.getInputStream()) {
            byte[] buffer = new byte[10240];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                session.sendMessage(new BinaryMessage(ByteBuffer.wrap(buffer, 0, bytesRead)));
            }
        } catch (Exception ignored) {
        } finally {
            try {
                session.close(CloseStatus.NORMAL);
            } catch (Exception ignored) {
            }
        }
    }

    @Async
    public void handlerErrorStream(Process process) {
        try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            String line;
            while ((line = errorReader.readLine()) != null) {
                log.error("Transcoding error ==> " + line);
            }
        } catch (Exception ignored) {
        }
    }

}
